home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7643 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: need for function prototypes
  5. Date: Tue, 27 Feb 96 20:10:58 GMT
  6. Organization: none
  7. Message-ID: <825451858snz@genesis.demon.co.uk>
  8. References: <4gutho$o1a@mn5.swip.net>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4gutho$o1a@mn5.swip.net>
  15.            chris.rossall@mailbox.swipnet.se "Chris Rossall" writes:
  16.  
  17. >Hello I am having trouble understanding why I should use function
  18. >prototypes. I mean,if the function is defined before it is used,the
  19. >compiler should have enough information about the parameters to
  20. >produce correct code anyway.
  21.  
  22. The first thing to do here is to make the terminology perfectly clear.
  23. Consider:
  24.  
  25.  
  26. 1. int foo();
  27.  
  28. 2. int foo(float);
  29.  
  30. 3. int foo(value)
  31.    float value;
  32.    {
  33.    }
  34.  
  35. 4. int foo(float value)
  36.    {
  37.    }
  38.  
  39. All of these are 'declarations'.
  40.  
  41. 3 and 4 are 'definitions' because they allocate storage (i.e. in this
  42. case include a function body).
  43.  
  44. Of these four only 2 and 4 contain prototypes i.e. the parameter list
  45. contains type information. In the case of 3 the parameter list is simply
  46. value and the type is specified elsewhere - it is not a prototype.
  47.  
  48. Only prototypes provide type information for the compiler to use with
  49. function calls. If I write:
  50.  
  51.    foo(1);
  52.  
  53. the action will depend on which of the four is in scope. With 1 and 3 the
  54. compiler will simply pass the integer value 1. Since this is incompatible
  55. with the parameter type the result is undefined behaviour. With 2 or 4
  56. in scope the compiler must convert the value to a float (where such a
  57. conversion is legal as it is in this case) and pass that. If the conversion
  58. is not legal the compiler must warn about it which provides important
  59. diagnostics.
  60.  
  61. The key case here is 3 - having such a definition in scope does not guarantee
  62. you any error checking or implicit conversion, although a particular compiler
  63. can generate any extra diagnostics it likes and one form of undefined
  64. behaviour is 'doing what seems reasonable'.
  65.  
  66. -- 
  67. -----------------------------------------
  68. Lawrence Kirby | fred@genesis.demon.co.uk
  69. Wilts, England | 70734.126@compuserve.com
  70. -----------------------------------------
  71.